<template>
	<view class="comp-box" style="padding: 24rpx;">
		<!-- 产品展示 -->
		<view class="part2" style="padding-bottom: 150rpx;">
		<!-- <view class="title-box u-flex u-row-between">
			<text class="title-text">产品展示</text>
		</view> -->
			<view style="background-color: #FFFFFF;border-radius: 20rpx;margin-bottom: 20rpx;padding: 0 20rpx;" class="isshow u-flex u-row-between">
				<text>是否展示企业产品</text>
				<switch :checked="isShowItem" @change="isShowItem = !isShowItem" color="rgba(29, 168, 254, 1)" style="transform: scale(0.8);"></switch>
			</view>
			<view class="part2-con u-p-t-20" @click="typeIndex = index" v-for="(item,index) in typeList" :key="index"
				style="margin-bottom: 20rpx;position: relative;padding: 0 10rpx;">
				
				<view class="type-all">
					<view class="type-name u-flex"
						style="background-color: rgba(242, 242, 242, 1);border-radius: 24rpx 24rpx 0rpx 0rpx;padding: 0 12rpx;">
						<text style="line-height: 120rpx;font-size: 32rpx;font-weight: bold;">类目名称</text>
						<view class="u-flex" style="background-color: #FFFFFF;margin-left: 10rpx; border-radius: 20rpx;">
							<input maxlength="8" style="background-color: #FFFFFF;height: 54rpx;flex: 1;" class=" u-m-l-10"
								type="text" value="" v-model="item[0] && item[0].subtitle" placeholder="请输入类目名称" />
							<text class="num-text">（{{item[index] && item[index].subtitle && item[index].subtitle.length || 0}}/8）</text>
						</view>
					</view>
					<view @click="proIndex = index2" class="form u-flex-col" v-for="(item2,index2) in item"
						:key="index2"
						style="background-color: rgba(247, 248, 252, 1);padding: 0 12rpx;box-sizing: border-box;">
						<view class="pro-list">
							<view class="form-item u-flex u-row-between" style="border-bottom: 1rpx solid #FFFFFF;">
								<view class="img-title">产品名称 <text style="color: #FF3434;margin-left: 5rpx;">*</text>
								</view>
								<view class="form-right u-flex">
									<input maxlength="8" v-model="item2.productName" type="text"
										value="" placeholder="请输入" />
									<text
										class="num-text">（{{item2.productName && item2.productName.length || 0}}/8）</text>
								</view>
							</view>
							<view class="img-con">
								<view class="img-title">产品图片<text
										style="color: #FF3434;margin-left: 5rpx;">*</text><text
										class="num-text">（{{item2.sendImg && item2.sendImg.length|| 0}}/4）</text>
								</view>
								<u-upload  :showProgress="false" @on-uploaded="uploadSuccess" @on-remove="uploadRemove"
									:action="`https://job.ydylmold.cn/base/upload/file`"
									:formData="{fileCode:134,fileType:100,fileParaName:'file'}" width="138rpx"
									height="138rpx" :fileList="item2.fileList" maxCount="4">
								</u-upload>
							</view>
							<view class="btns u-flex u-row-right u-m-t-40 u-m-b-10" @click="delPro(item2,index2)">
								<text class="del-button">
									删除产品
								</text>
							</view>

						</view>
					</view>
					<view class="add-type" @click="insertPro(index,index2)">+ 添加产品</view>
				</view>
				<view class="u-flex" @click="delType(item,index)">
					<u-image width="22rpx" height="26rpx"
						src="https://job.ydylmold.cn/mingpian/image/editImg/del1.png"></u-image>
					<text class="u-m-x-12 del-text" style="line-height: 100rpx;">删除该类目</text>
				</view>
			</view>
		</view>
		<view class="fix-btn"
			style="z-index: 999;position: fixed;bottom: 0;right: 0;padding: 0rpx 24rpx 10rpx 24rpx;width: 100%;background-color: #FFFFFF;">
			<button type="primary" @click="$u.throttle(saveItem, 2000)"
				style=" background-color: rgba(29, 168, 254, 1);margin-top: 20rpx;border-radius: 48rpx;">保存</button>
		</view>
		<view class="fix-add u-flex u-row-center u-col-center" @click="addType">
			<u-image width="40rpx" height="40rpx" src="https://job.ydylmold.cn/mingpian/image/editImg/add-img.png">
			</u-image>
		</view>
	</view>
</template>

<script>
	import {
		queryUsrCompanyStationList,
		insertCompanyStation,
		deleteUsrCompanyStationById
	} from '@/common/api/auth.js'
	import upVideo from '@/utils/uploadVideo.js'
	import {
		getToken
	} from '@/utils/token.js'
	export default {
		data() {
			return {
				typeList: [
					[{
						updateImage: "",
						fileName: "",
						productVideo: "",
						stationId: "",
						companyId: getToken('useNum'),
						moduleNo: "ydylapp1003",
						stationType: "1",
						subtitle: "",
						productName: "",
						sendImg:[],
						state:1
					}]
				],
				proIndex: 0,
				typeIndex: 0,
				canSave: {
					proSave: true,
				},
				isChange: {
					proData: false,
				},
				isShowItem:false
			}
		},
		onLoad: function() {
			this.init()
		},
		methods: {
			setIndex(index,index2){
			},
			//删除某个产品
			delPro(item, index) {
				uni.showModal({
					title: '提示',
					content: '您确定要删除' + item.productName + '吗?',
					success: (e) => {
						if (e.confirm) {
							if (item.stationId) {
								deleteUsrCompanyStationById({
									stationId: item.stationId
								}).then(res => {
									if (res.data && res.data.code == 1) {
										this.$u.toast(res.data.msg || res.data.message || '删除成功')
										this.typeList[this.typeIndex].splice(index, 1)
									} else {
										this.$u.toast(res.data.msg || res.data.message || '删除失败')
									}
									this.$store.commit('isFresh', true)
								})
							} else {
								this.typeList[this.typeIndex].splice(index, 1)
							}
						}
					}
				})
			},

			// 初始化数据
			async init() {
				let res = await this.queryUsrCompanyStationList()
				if (res.data && res.data.code == 1) {
					let acInfo = {}
					// 数组分类
					let data = res.data && res.data.listData
					let arrAll = data.filter(m => {
						return m.stationId != ''
					})
					this.isShowItem = arrAll[0].state == 1?true:false
					if(arrAll && arrAll.length){
						arrAll.forEach((pro, idx) => {
							if (pro.imgName) {
								pro.sendImg = pro.imgName.split(',')
								pro.fileList = pro.imgName.split(',').map(v => {
									return {
										url: 'https://www.ydylmold.cn/images/ydylapp/usrCompanyStation/mainProductsImage/' +
											v
									}
								})
							}
							if (!pro.subtitle) {
								pro.subtitle = '其他分类'
							}
						})
						//产品数组按照子标题分类
						let arr1 = arrAll.reduce((acc, obj) => {
							let key = obj['subtitle']
							if (!acc[key]) {
								acc[key] = []
							}
							acc[key].push(obj)
							return acc
						}, {})
						let arr2 = []
						for (let key in arr1) {
							arr2.push(arr1[key])
						}
						this.typeList = arr2
					}
					

				}
			},
			//公司更多数据详情
			queryUsrCompanyStationList() {
				return queryUsrCompanyStationList({
					companyNo: getToken('useNum'),
					stationType:1
				})
			},
			//保存产品
			saveItem() {
				let params = {}
				this.checkSave(1)
				if (this.canSave.proSave) {
					let arr = []
					let sendArr = []
					this.typeList.forEach((item, index) => {
						if (item && item.length) {
							item.forEach((item2, index2) => {
								sendArr.push({
									updateImage: item2.sendImg.join(','),
									stationId: item2.stationId || "",
									companyId: item2.companyId || getToken('useNum'),
									moduleNo: 'ydylapp1002',
									stationType: item2.stationType || 1,
									productName: item2.productName || '',
									subtitle: item2.subtitle || '',
									state:this.isShowItem?1:0
								})
							})
						}
					})
					params.jsonData = JSON.stringify(sendArr)
					this.editFun(params)
				}
			},
			editFun(params) {
				insertCompanyStation(params).then(res => {
					if (res.data && res.data.code == 1) {
						uni.hideLoading()
						this.$u.toast('保存成功')
						setTimeout(()=>{
							uni.navigateBack()
						},500)
						this.$store.commit('isFresh', true)
					} else {
						this.$u.toast('保存失败')
					}
				})
			},
			delType(item,index){
				uni.showModal({
					title: '提示',
					content: '您确定要删除' + (item[0] && item[0].subtitle) + '吗?',
					success: (e) => {
						if (e.confirm) {
							if (item[0] && item[0].stationId) {
								deleteUsrCompanyStationById({
									stationId: item.map(v=>{return v.stationId}).join(',')
								}).then(res => {
									let data = res.data
									if (data.code == 1) {
										this.$u.toast(data.msg || data.message || '删除成功')
										this.typeList.splice(index,1)
									} else {
										this.$u.toast(data.msg || data.message || '删除失败')
									}
									this.$store.commit('isFresh', true)
								})
							} else {
								this.typeList.splice(index,1)
							}
						}
					}
				})
			},
			//添加某类产品
			addType() {
				this.checkSave(1)
				if (this.canSave.proSave) {
					this.typeList.push(
						[{
							updateImage: "",
							fileName: "",
							productVideo: "",
							stationId: "",
							companyId: getToken('useNum'),
							moduleNo: "ydylapp1003",
							stationType: "1",
							subtitle: "",
							productName: ""
						}]
					)
					setTimeout(()=>{
						uni.pageScrollTo({
							scrollTop:9999999999999,
							duration:300
						})
					},300)
				}
			},
			//添加单个产品
			insertPro(index, index2) {
				this.typeIndex = index
				this.proIndex = index2
				this.isChange.proData = true
				this.checkSave(2)
				if (this.canSave.proSave) {
					this.typeList[this.typeIndex].push({
						updateImage: "",
						fileName: "",
						productVideo: "",
						stationId: "",
						companyId: getToken('useNum'),
						moduleNo: "ydylapp1003",
						stationType: "1",
						subtitle: this.typeList[this.typeIndex][0] && this.typeList[this.typeIndex][0].subtitle || '',
						productName: "",
						sendImg:[]
					})
				}
			},
			checkSave(type) {
				this.canSave.proSave = true
				if (type == 1) {//判断产品是否可以添加
					this.typeList.forEach((item, index) => {
						if (item && item.length) {
							item.forEach((item2, index2) => {
								if (!item2.productName) {
									this.$u.toast('第' + (index + 1) + '个分类,名称未填完整')
									this.canSave.proSave = false
								}
								if (item2.sendImg && item2.sendImg.length == 0) {
									this.$u.toast('第' + (index + 1) + '个分类,图片未填完整')
									this.canSave.proSave = false
								}
							})
						}
					})
				} else if (type == 2) {//判断分类是否可以添加
					this.typeList[this.typeIndex].forEach((item, index) => {
						if (!item.productName) {
							this.$u.toast('第' + (index + 1) + '个产品,名称未填完整')
							this.canSave.proSave = false
						}
						if (item.sendImg && item.sendImg.length == 0) {
							this.$u.toast('第' + (index + 1) + '个产品,图片未填完整')
							this.canSave.proSave = false
						}
					})
				}


			},

			//产品图片上传
			uploadRemove(e, list, index, delItem) {
				this.isChange.proData = true
				let arr = this.typeList[this.typeIndex]
				arr[this.proIndex].sendImg.splice(e, 1)
				this.typeList[this.typeIndex] = arr
			},
			getImgArr(data) {
				let arrImg = []
				let arr = []
				data.forEach(v => {
					if (v.url && !v.response) {
						arr = v.url.split('/')
						arrImg.push(arr[arr.length - 1])
					} else {
						arrImg.push(v.response.data)
					}
				})
				return arrImg
			},
			//产品图片上传成功
			uploadSuccess(e) {
				this.isChange.proData = true
				let acArr = this.typeList[this.typeIndex]
				acArr[this.proIndex].sendImg = this.getImgArr(e)
				this.typeList[this.typeIndex] = acArr
			},

		}
	}
</script>

<style lang="scss">
	@import "./css/edit.scss";
	.num-text {
		font-size: 24rpx;
		font-weight: 500;
		color: rgba(128, 128, 128, 1);
		flex: none;
	}

	input {
		background-color: #FFFFFF;
		flex: 1;
		height: 54rpx;
	}

	.form-right {
		flex: 1;
		border-bottom: 1rpx solid rgba(217, 217, 217, 1);
		margin-left: 10rpx;
		height: 54rpx;
	}

	.del-button {
		border: 1rpx solid rgba(56, 56, 56, 1);
		font-size: 24rpx;
		font-weight: bold;
		color: rgba(56, 56, 56, 1);
		padding: 10rpx 16rpx;
		border-radius: 30rpx;
		text-align: right;
	}

	.add-type {
		background-color: rgba(247, 248, 252, 1);
		border-radius: 0 0 24rpx 24rpx;
		font-size: 24rpx;
	}
</style>
